package com.base.pay.wx;

import com.base.mapper.voipmapper.UsersConfigNewMapper;
import com.base.mapper.voipmapper.UsersMapper;
import com.base.pay.exception.WxRuntimeException;
import com.base.pay.wx.tool.WXPay;
import com.base.pay.wx.tool.WxConfig;
import com.base.po.voip.Users;
import com.base.po.voip.UsersConfigNew;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author XiFYuW
 * @since  2020/09/13 8:38
 */
@Component
@Slf4j
public class WxFactoryConfig {

    private final UsersMapper usersMapper;

    private final UsersConfigNewMapper usersConfigNewMapper;

    @Value("${system.wx-cre-path}")
    private String wxCrePath = "";

    public WxFactoryConfig(UsersMapper usersMapper, UsersConfigNewMapper usersConfigNewMapper) {
        this.usersMapper = usersMapper;
        this.usersConfigNewMapper = usersConfigNewMapper;
    }

    public WXPay wxPay(final String parentId) {
        try {
            final Users users = usersMapper.selectByPrimaryKey(parentId);
            if (users != null) {
                final WxConfig wxConfig = new WxConfig(
                        users.getWxappid(),
                        users.getWxmchid(),
                        users.getWxapikey(),
                        wxCrePath/*C:\Program Files\Apache Software Foundation\cres\1603923711_20201107_cert\apiclient_cert.p12*/);
                final WXPay wxPay = new WXPay(wxConfig);
                wxPay.checkWXPayConfig();
                return wxPay;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        throw new WxRuntimeException("微信支付配置错误");
    }

    public WXPay wxJsPay(final String parentId) {
        try {
            final UsersConfigNew usersConfigNew = usersConfigNewMapper.selectByParentId(parentId);
            final Users users = usersMapper.selectByPrimaryKey(parentId);
            if (users != null && usersConfigNew != null) {
                final WxConfig wxConfig = new WxConfig(
                        usersConfigNew.getWxMpAppid(),
                        users.getWxmchid(),
                        users.getWxapikey(),
                        wxCrePath);
                final WXPay wxJsPay = new WXPay(wxConfig);
                wxJsPay.checkWXPayConfig();
                return wxJsPay;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        throw new WxRuntimeException("微信jsapi支付配置错误");
    }
}
